package com.konsung.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.konsung.bean.PatientBean;
import com.konsung.healthfile.R;
import com.konsung.ui.HealthFileActivity;
import com.konsung.ui.defineview.RoundImageView;
import com.konsung.util.IdCardUtil;
import com.konsung.util.SpUtils;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 类功能：
 */

public class PatientListAdapter extends BaseAdapter {

    private final List<PatientBean> data;
    private final Context context;
    private final LayoutInflater layoutInflater;
    private List<String> deletePatient; //存储删除的居民身份证
    private List<PatientBean> notDeletePatient; //存储不删除的居民
    private boolean isAllSeleted; // 是否点击了全选
    private long allSize; //数据库居民数据总的长度

    /**
     * 构造器
     * @param context 上下文
     * @param data 文本数据集
     * @param allSize 所有数据的长度
     */
    public PatientListAdapter(Context context, List<PatientBean> data, long allSize) {
        this.data = data;
        this.context = context;
        this.allSize = allSize;
        layoutInflater = LayoutInflater.from(context);
        deletePatient = new ArrayList<>();
        notDeletePatient = new ArrayList<>();
    }

    @Override
    public int getCount() {
        if (data != null) {
            return data.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.item_patient_list, null);
            ButterKnife.bind(viewHolder, convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final PatientBean patientBean = data.get(position);
        viewHolder.tvSerial.setText(position + 1 + "");
        viewHolder.tvAge.setText(patientBean.getAge() + UiUtils.getString(R.string.year));
        viewHolder.tvName.setText(patientBean.getName());
        final String idcard = patientBean.getIdcard();
        viewHolder.tvIdCardNumber.setText(idcard);
        viewHolder.tvSex.setText(IdCardUtil.getSexFormDB(patientBean.getSex()));
        setOtherOperation(viewHolder.tvOtherOperation, idcard);
        viewHolder.ivDelete.setVisibility(View.INVISIBLE);
        //获取居民头像
        UiUtils.setHeadPhoto(viewHolder.ivIcon, patientBean);
        viewHolder.ivIcon.setVisibility(View.VISIBLE);
        //设置居民所有测量信息是否上传的状态
        if (patientBean.getIsUploadAll()) {
            //已经上传
            viewHolder.tvUploadState.setText(UiUtils.getString(R.string.uploaded));
            viewHolder.tvUploadState.setTextColor(context.getResources()
                    .getColor(R.color.white));
        } else {
            //未上传
            viewHolder.tvUploadState.setText(UiUtils.getString(R.string.unUpload));
            viewHolder.tvUploadState.setTextColor(context.getResources().getColor(R.color.red));
        }
        viewHolder.tvOtherOperation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String operation = viewHolder.tvOtherOperation.getText().toString();
                if (!operation.equals(UiUtils.getString(R.string.current_patient))) {
                    UiUtils.setCurrentPatient(idcard);
                    ToastUtils.showShortToast(R.string.set_success);
                    notifyDataSetChanged();
                }
            }
        });

        if (isAllSeleted && !deletePatient.contains(idcard)
                && !notDeletePatient.contains(patientBean)) {
            deletePatient.add(idcard);
        } else if (!isAllSeleted && !notDeletePatient.contains(patientBean)) {
            notDeletePatient.add(patientBean);
        }

        viewHolder.cbxSelect.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                        if (isChecked) {
                            if (buttonView.getId() == position
                                    && !deletePatient.contains(idcard)) {

                                deletePatient.add(idcard);
                                if (notDeletePatient.contains(patientBean)) {
                                    notDeletePatient.remove(patientBean);
                                }
                            }
                            if (isAllSeleted && notDeletePatient.size() == 0) {
                                ((HealthFileActivity) context).setAllSelect(true);
                            } else if (!isAllSeleted && deletePatient.size() == allSize) {
                                ((HealthFileActivity) context).setAllSelect(true);
                            }
                        } else {
                            if (buttonView.getId() == position
                                    && deletePatient.contains(idcard)) {

                                if (!notDeletePatient.contains(patientBean)) {
                                    notDeletePatient.add(patientBean);
                                }
                                deletePatient.remove(idcard);
                                ((HealthFileActivity) context).setAllSelect(false);
                            }
                        }
                    }
                });
        viewHolder.cbxSelect.setId(position);
        if (isAllSeleted) { //全选状态下，按照不删除的集合来判断
            if (notDeletePatient.contains(patientBean)) {
                viewHolder.cbxSelect.setChecked(false);
            } else {
                viewHolder.cbxSelect.setChecked(true);
            }
        } else { //非全选状态下，按照删除的集合来判断
            if (deletePatient.contains(idcard)) {
                viewHolder.cbxSelect.setChecked(true);
            } else {
                viewHolder.cbxSelect.setChecked(false);
            }
        }
        //更新建档状态
        if (UiUtils.isShuYangArea()) {
            viewHolder.tvFilestate.setVisibility(View.VISIBLE);
            if (patientBean.getIsFileCreat()) {
                viewHolder.tvFilestate.setText(context.getString(R.string.have_file));
            } else {
                viewHolder.tvFilestate.setText(context.getString(R.string.no_file));
            }
        } else {
            viewHolder.tvFilestate.setVisibility(View.GONE);
        }

        return convertView;
    }

    /**
     * 设置总的长度
     * @param allSize 总的长度
     */
    public void setAllSize(long allSize) {
        this.allSize = allSize;
    }

    /**
     * 获取deletePatient的值
     *
     * @return deletePatient deletePatient值
     */
    public List<String> getDeletePatient() {
        return deletePatient;
    }

    /**
     * 设置删除按钮是否全选
     * @param isChecked 是否全选
     */
    public void setAllDeleteState(boolean isChecked) {
        isAllSeleted = isChecked;
        deletePatient.clear();
        if (isChecked) {
            for (PatientBean bean : data) {
                deletePatient.add(bean.getIdcard());
            }
        }
        notDeletePatient.clear();
        notifyDataSetChanged();
    }

    /**
     * 获取没有删除的居民
     * @return List<PatientBean>
     */
    public List<PatientBean> getNotDeletePatient() {

        return notDeletePatient;
    }

    /**
     * 视图容器
     */
    class ViewHolder {
        @BindView(R.id.cbx_select)
        CheckBox cbxSelect;
        @BindView(R.id.tv_serial)
        TextView tvSerial;
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_id_card_number)
        TextView tvIdCardNumber;
        @BindView(R.id.tv_sex)
        TextView tvSex;
        @BindView(R.id.tv_age)
        TextView tvAge;
        @BindView(R.id.tv_other_operation)
        TextView tvOtherOperation;
        @BindView(R.id.tv_filestate)
        TextView tvFilestate;
        @BindView(R.id.iv_close)
        ImageView ivDelete;
        @BindView(R.id.iv_icon)
        RoundImageView ivIcon;
        @BindView(R.id.tv_upload_state)
        TextView tvUploadState;
    }

    /**
     * 判断是否当前居民并且设置文本内容
     * @param tv 文本控件
     * @param idCard 身份证号码
     */
    private void setOtherOperation(TextView tv, String idCard) {
        String currentIdCard = SpUtils.getSp(context, GlobalConstant.APP_CONFIG,
                GlobalConstant.CURRENT_PATIENT, "");
        if (currentIdCard.equals(idCard)) {
            tv.setClickable(false);
            tv.setText(R.string.current_patient);
            tv.setTextColor(context.getResources().getColor(R.color.white));
        } else {
            tv.setTextColor(context.getResources().getColor(R.color.red));
            tv.setText(R.string.setting_current_patient);
            tv.setClickable(true);
        }
    }
}
